package com.ccb.channel.zj;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.ccb.util.DateUtil;
import com.ccb.util.Record;
import com.ccb.util.RecordType;


public class ZJRecordGenerator implements RecordGenerator {

	public MapperResult parseData(String value) {
		String[] fields = StringUtils.split(value, ',');		
		Map<String, String> map = new LinkedHashMap<String, String>();
		for(String segment : fields) {
			String label = StringUtils.substringBefore(segment, ":").trim();
			String val = StringUtils.substringAfter(segment, ":");
			map.put(label, val);
		}
		
		String group;
		Record record = new Record();
		if(map.containsKey("CDFWINMS-SYS-REQ-TIME")){
			try {
				String dateTime=map.get("CDFWINMS-SYS-REQ-TIME").trim();
				String formatStr=DateUtil.date2Str("yyyy-MM-dd HH:mm:ss.SSS", DateUtil.str2Date("yyyyMMddHHmmssSSS",dateTime));
				Timestamp time=Timestamp.valueOf(formatStr);
				record.setTime(time);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		if(map.containsKey("CDFWINMS-SEC-ERROR-CODE")){
			record.setResponseCode(map.get("CDFWINMS-SEC-ERROR-CODE"));
		}
		
		StringBuilder sb = new StringBuilder();		
		if(map.containsKey("CDFWINMS-CICS-TRNID")) {
			group = map.get("CDFWINMS-SEC-TX-CODE");	
			record.setServiceId(group);
		//	record.setType(RecordType.REQUEST);
			record.setRecordType(RecordType.REQUEST);
			sb.append(map.get("CDFWINMS-SYS-EVT-TRACE-ID")).append(map.get("CDFWINMS-SYS-SND-SERIAL-NO")).append(map.get("CDFWINMS-SYS-TX-TYPE"));
			record.setOriginalData(value);
			record.setData((JSONObject)JSONObject.toJSON(map));
		}else {
			group = map.get("CDFWOPMS-SEC-TX-CODE");	
			record.setServiceId(group);
			record.setRecordType(RecordType.RESPONSE);
			sb.append(map.get("CDFWOPMS-SYS-EVT-TRACE-ID")).append(map.get("CDFWOPMS-SYS-SND-SERIAL-NO")).append(map.get("CDFWOPMS-SYS-TX-TYPE"));
			record.setOriginalData(value);
			record.setData((JSONObject)JSONObject.toJSON(map));
		}
					
		record.setUid(sb.toString());
		
		
		return new MapperResult(record.getUid(), record);
	}

}
